
/* -*- C++ -*- */

//=============================================================================
/*
* @author Feloweria <380374483@qq.com>
* Copyright (C) Feloweria
*
* $ID 2014-05-14 11:24:02 AM
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* @version 1.0
*/
//=============================================================================

FELOWRIA_BEGIN

inline SocketBuffer::SocketBuffer(char *buffer, char *buffer_end)
:buffer(buffer), buffer_end(buffer_end), data(buffer), data_end(buffer)
{
    ASSERT(buffer && buffer_end && buffer < buffer_end);
}

inline SocketBuffer::~SocketBuffer()
{

}

inline int32 SocketBuffer::Readable() const
{
	int32 readable = static_cast<int32>(data_end - data);

	if (readable >= 0)
		return readable;

	return static_cast<int32>(buffer_end - buffer + readable);
}

inline void SocketBuffer::Readable(char *&rdPtr, int32 &size)
{
	if(data != buffer_end)
	{
		rdPtr = data;
		size = ReadSize();
	}else
	{
		rdPtr = buffer;
		size = Readable();
	}
}
inline int32 SocketBuffer::Writable() const
{
	int32 writable = static_cast<int32>(data - data_end);

	if (writable > 0)
		return writable - 1;

	return static_cast<int32>(buffer_end - buffer + writable - 1);
}
inline void SocketBuffer::Writable(char *&wdPtr, int32 &size)
{
	if(data_end != buffer_end)
	{
		wdPtr = data_end;
		size = WriteSize();
	}else
	{
		wdPtr = buffer;
		size = Writable();
	}
}

inline int32  SocketBuffer::WriteSize() const
{
	int32 write_size = static_cast<int32>(data - data_end);
	if (write_size <= 0)
		return static_cast<int32>(buffer_end - data_end);
	
	return static_cast<int32>(write_size - 1);
}

inline int32  SocketBuffer::ReadSize() const
{
	int32 read_size = static_cast<int32>(data_end - data);
	if (read_size < 0)
		return static_cast<int32>(buffer_end - data);
	
	return read_size;
}

inline void SocketBuffer::Reset()
{
	data_end = buffer;
	data = buffer;
}

FELOWRIA_END
